#include "rdtsc.h"
#include "cpu.h"
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/time.h>

//# define DEBUG

//int main(int argc, char* argv[])
unsigned long long get_current_CPU_freq()
{
//	if(argc != 1)
//		exit(-1);

	unsigned long long cycle_s;
	unsigned long long cycle_e;
	unsigned long long cycle;
	double time_duration;
	unsigned long long CPU_freq;
	
	struct timeval tv1;
	struct timeval tv2;
	time_t ts1, ts2, tus1, tus2;



// Test_RDTSC: this code test rdtsc the value return by rdtsc is correctly caculated
/*	int i;
	for(i = 0; i < 100; i++)
	{
		cycle = rdtsc();
		printf("%llu\n", cycle);
		usleep(100000);
	}
*/

// Test_CLOCK_T: this code test measurement using clock_t clock(void)
/*	clock_t start, end;
	start = clock();
//	sleep(10);
	int bar;
	for(int i = 0; i < 10000; i++)
		for(int j = 0; j < 10000; j++)
			for(int k = 0; k < 10000; k++)
			{
				bar++;
			}
	end = clock();
	printf("start = %lf\n", (double) start);
	printf("end = %lf\n", (double) end);
	printf("running time: %lf\n", (double)(end - start)/CLOCKS_PER_SEC);
*/
	cycle_s = rdtsc();
	gettimeofday(&tv1, NULL);
 	ts1 = tv1.tv_sec;
	tus1 = tv1.tv_usec;
	#ifdef DEBUG
	printf("cycle start: %llu\n", cycle_s);
	#endif
	sleep(1);
	//	usleep(100000);
	cycle_e = rdtsc();
	gettimeofday(&tv2, NULL);
//	ts1 = tv1.tv_sec;
//	tus1 = tv1.tv_usec;
	ts2 = tv2.tv_sec;
	tus2 = tv2.tv_usec;
	#ifdef DEBUG
	printf("cycle end: %llu\n", cycle_e);
	#endif
	cycle = cycle_e - cycle_s;
	#ifdef DEBUG
	printf("cycle: %llu\n", cycle);
	#endif
//	time  = (double) cycle / (double) CPU_FQ;
//	printf("time: %lf\n", time);
	time_duration = ((double)ts2 + (double)tus2/1000000) - ((double)ts1 + (double)tus1/1000000);
	#ifdef DEBUG
	printf("time: %lf\n", time_duration);
	#endif
	CPU_freq = cycle / time_duration;
	#ifdef DEBUG
	printf("Current CPU freqency is %llu\n", CPU_freq);
	#endif
	
	return CPU_freq;
	
//	return 0;
}
